import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Channel, ImageSlide, ImageSlideComponent } from 'src/app/shared/components';
import { HomeService } from '../../services';
import { filter, map, switchMap, tap } from 'rxjs/operators';
import { Observable, Subscription } from 'rxjs';
import { Ad, Product } from 'src/app/shared/domain';

@Component({
  selector: 'app-home-detail',
  templateUrl: './home-detail.component.html',
  styleUrls: ['./home-detail.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HomeDetailComponent implements OnInit, OnDestroy {
  constructor(private route: ActivatedRoute, private service: HomeService, private cd: ChangeDetectorRef) { }
  @ViewChild(ImageSlideComponent, {static: true}) imgSlider: ImageSlideComponent;
  selectedTabLink$: Observable<string>;
  imageSlides$: Observable<ImageSlide[]>;
  channels$: Observable<Channel[]>;
  ad$: Observable<Ad>;
  products$: Observable<Product[]>;
  sub: Subscription;

  ngOnInit() {
    this.selectedTabLink$ = this.route.paramMap.pipe(
      filter(params => params.has('tabLink')),
      map(params => params.get('tabLink'))
    );

    this.sub = this.route.queryParamMap.subscribe(params => {
      console.log('查询参数', params)
    });
    
    this.imageSlides$ = this.service.getBanners();
    this.channels$ = this.service.getChannels();

    this.ad$ = this.selectedTabLink$.pipe(
      switchMap(tab => this.service.getAdByTab(tab)),
      filter(ads => ads.length > 0),
      map(ads => ads[0])
    )

    this.products$ = this.selectedTabLink$.pipe(
      switchMap(tab => this.service.getProductByTab(tab))
    )
  }

  ngOnDestroy(): void {
    this.sub.unsubscribe();
  }  
}
